package com.cq.hd.admin.controller;

import com.cq.hd.admin.annotation.RequiresPermissionsDesc;
import com.cq.hd.admin.dto.DownloadInviteBusinessUrlImgDto;
import com.cq.hd.common.pagination.Page;
import com.cq.hd.common.response.Result;
import com.cq.hd.common.response.ResultGenerator;
import com.cq.hd.common.response.Throw;
import com.cq.hd.common.utils.StringUtils;
import com.cq.hd.member.api.TbInviteBusinessUrlApi;
import com.cq.hd.member.api.dto.EnterBusinessPageDto;
import com.cq.hd.member.api.dto.InviteBusinessUrlPageDto;
import com.cq.hd.member.api.dto.InviteBusinessUrlSaveDto;
import com.cq.hd.member.api.vo.EnterBusinessPageVo;
import com.cq.hd.member.api.vo.InviteBusinessUrlPageVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

@Api(tags = "商家邀请链接相关接口")
@Slf4j
@RestController
@RequestMapping("/inviteBusinessUrl")
public class TbInviteBusinessUrlController extends BaseController {

    private TbInviteBusinessUrlApi inviteBusinessUrlApi;

    @Autowired
    public void setInviteBusinessUrlApi(TbInviteBusinessUrlApi inviteBusinessUrlApi) {
        this.inviteBusinessUrlApi = inviteBusinessUrlApi;
    }

    @ApiOperation(value = "保存邀请商家链接")
    @ApiImplicitParam(name = "inviteBusinessUrlSaveDto", value = "保存参数", paramType = "body", dataType = "InviteBusinessUrlSaveDto")
    @RequiresPermissions("business:inviteBusinessUrl:save")
    @RequiresPermissionsDesc(menu = {"商家管理", "商家邀请管理"}, button = "保存")
    @PostMapping("/save")
    public Result<Object> saveInviteBusinessUrl(@Validated @RequestBody InviteBusinessUrlSaveDto inviteBusinessUrlSaveDto) {
        return inviteBusinessUrlApi.saveInviteBusinessUrl(inviteBusinessUrlSaveDto);
    }

    @ApiOperation(value = "邀请商家链接列表")
    @ApiResponse(response = InviteBusinessUrlPageVo.class, code = 200, message = "接口返回对象参数")
    @RequiresPermissions("business:inviteBusinessUrl:list")
    @RequiresPermissionsDesc(menu = {"商家管理", "商家邀请管理"}, button = "查询")
    @GetMapping("/page")
    public Result<Page<InviteBusinessUrlPageVo>> pageInviteBusinessUrl(InviteBusinessUrlPageDto inviteBusinessUrlPageDto) {
        return inviteBusinessUrlApi.pageInviteBusinessUrl(inviteBusinessUrlPageDto);
    }

    @ApiOperation(value = "删除邀请商家链接")
    @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "Long")
    @RequiresPermissions("business:inviteBusinessUrl:delete")
    @RequiresPermissionsDesc(menu = {"商家管理", "商家邀请管理"}, button = "删除")
    @PostMapping("/delete")
    public Result<Object> deleteInviteBusinessUrl(Long id) {
        inviteBusinessUrlApi.deleteInviteBusinessUrl(id);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "查看入驻商家")
    @ApiResponse(response = EnterBusinessPageVo.class, code = 200, message = "接口返回对象参数")
    @RequiresPermissions("business:inviteEnterBusiness:list")
    @RequiresPermissionsDesc(menu = {"商家管理", "商家邀请管理"}, button = "查看入驻商家")
    @GetMapping("/pageEnterBusiness")
    public Result<Page<EnterBusinessPageVo>> pageEnterBusiness(EnterBusinessPageDto enterBusinessPageDto) {
        return inviteBusinessUrlApi.pageEnterBusiness(enterBusinessPageDto);
    }

    @ApiOperation(value = "下载邀请商家二维码")
    @PostMapping("/download")
    public void download(@RequestBody DownloadInviteBusinessUrlImgDto downloadInviteBusinessUrlImgDto, HttpServletResponse response) {
        Long id = downloadInviteBusinessUrlImgDto.getId();
        if (id == null) {
            Throw.isBusinessException("请选择下载的邀请商家二维码");
        }

        InviteBusinessUrlPageVo inviteBusinessUrlPageVo = inviteBusinessUrlApi.getById(id).unpack();
        if (inviteBusinessUrlPageVo == null) {
            Throw.isBusinessException("未找到下载的邀请商家二维码");
        }

        String miniImgUrl = inviteBusinessUrlPageVo.getMiniImgUrl();
        String inviteName = inviteBusinessUrlPageVo.getInviteName();
        if (StringUtils.isBlank(miniImgUrl) || StringUtils.isBlank(inviteName)) {
            Throw.isBusinessException("下载参数错误");
        }

        OutputStream outputStream = null;
        try {
            URL url = new URL(URLEncoder.encode(miniImgUrl, "utf-8")
                    .replaceAll("%3A", ":").replaceAll("%2F", "/")
                    .replaceAll("%2C", ",").replaceAll("%7B", "{")
                    .replaceAll("%3F", "?").replaceAll("%7D", "}")
                    .replaceAll("%26", "&").replaceAll("%3D", "="));
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setConnectTimeout(1000);
            httpURLConnection.setReadTimeout(1000);
            InputStream inputStream = httpURLConnection.getInputStream();

            // 处理新的文件名称
            String extension = "";
            String path = url.getPath();
            int lastDotIndex = path.lastIndexOf('.');
            if (lastDotIndex != -1 && lastDotIndex < path.length() - 1) {
                extension = path.substring(lastDotIndex + 1).toLowerCase();
            } else {
                log.error("小程序码图片地址错误, miniImgUrl:{}", miniImgUrl);
                Throw.isBusinessException("下载参数错误");
            }
            String fileName = inviteName + "." + extension;

            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD, PUT");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "*");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            outputStream = response.getOutputStream();
            byte[] b = new byte[1024];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                outputStream.write(b, 0, length);
            }
        } catch (Exception e) {
            log.error("下载邀请商家二维码失败, inviteName:{}, 原因:{}", inviteName, e.getMessage());
            Throw.isBusinessException("下载失败");
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        }
    }

}
